import React, { useState, useEffect } from 'react'
import { TouchableHighlight, StyleSheet, TouchableOpacity, Text, View, Image, TextInput, Dimensions, Modal, ImageBackground } from 'react-native';
import { Entypo } from '@expo/vector-icons';
import * as FileSystem from 'expo-file-system';
import Lightbox from 'react-native-lightbox';
import * as ImagePicker from 'expo-image-picker';
import { ActionSheet } from 'antd-mobile-rn';
import { useAuth } from '../../context/AuthProvider';
import axios from '../../api/axios';
import { AntDesign } from '@expo/vector-icons';
const screenW = Dimensions.get('window').width;
const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} style={
            {
                justifyContent: 'center',
                alignItems: 'center',
                padding: 2,
                ...style
            }
        }>
            <Text style={{ color: color }}>{children}</Text>
        </TouchableOpacity>
    )
}
const CropDetail = ({ navigation, route }) => {
    const [showImg, setShowImg] = useState(false)
    const imageUrl = route.params.imageUrl
    const id = route.params.id
    const cropsid = route.params.cropsid
    const [imgArr, setImgArr] = useState([])
    const [previewImg, setPreviewImg] = useState('')
    const [clicked, setClicked] = useState('none')
    const [base64, setBase64] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [value, onChangeText] = useState("")
    const [eff, setEff] = useState(0)
    const [array, setArray] = useState([])
    const { user } = useAuth()
    console.log(cropsid);
    console.log(route.params);
    var base64arr = []
    var arr = []
    useEffect(() => {
        console.log(11111);
        console.log();
        console.log(imageUrl);
        navigation.setOptions({
            headerShown: false,
            headerLeft: () => (
                <Entypo name="chevron-thin-left" size={22} color="black" onPress={() => { setImgArr([]), navigation.goBack }} />
            )
        })
        setImgArr([...imgArr, ...imageUrl])
    }, [imageUrl])
    useEffect(()=>{
        if(eff>0){
            setImgArr(array)
        } else{
            setImgArr([...imgArr, ...imageUrl])
        }
    }, [array])
    // 选择图片
    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            // allowsEditing: true,
            aspect: [3, 3],
            quality: 1,
            useNativeDriver: true,
            allowsMultipleSelection: true
        });
        if (!result.canceled) {
            console.log(result.assets);
            for (let i = 0; i < result.assets.length; i++) {
                arr.push(result.assets[i].uri)
            }
            setImgArr([...imgArr, ...arr])
            setTimeout(() => {
                console.log(1591234569);
                arr = []
            }, 10)
        }
    }
    const showActionSheet = () => {
        const BUTTONS = [
            <Text onPress={pickImage} >从相册选择</Text>,
            '取消',
        ]
        ActionSheet.showActionSheetWithOptions(
            {
                options: BUTTONS,
                cancelButtonIndex: 1,
                useNativeDriver: true
            },
            (buttonIndex) => {
                setClicked(BUTTONS[buttonIndex])
                if (buttonIndex == 0) {
                    pickImage()
                }
            },
        )
    }
    const showModal = (item) => {
        // setModalVisible(true);
        setShowImg(!showImg);
        return <ImageBackground source={{ uri: item }} style={{ width: '100%', height: '100%' }}>

        </ImageBackground>
    }
    // 记录按钮
    const publish = async () => {
        console.log(imgArr);
        console.log(imgArr.length);
        for (let i = 0; i < imgArr.length; i++) {
            console.log(i);
            let base = await FileSystem.readAsStringAsync(imgArr[i], { encoding: 'base64' })
            // console.log(base);
            // console.log([...base64, base].length);
            setBase64([...base64, base])
            base64arr.push(base)
            // console.log(base64);
            if (i == imgArr.length - 1) {
                // console.log(base64.length);
                console.log(base64arr.length);
                console.log(66666666);
                // console.log([...base64, base].length);
                axios.post('/recordlist/upload', { userid: user.userid, recordtext: value, id: id, cropsid: cropsid, img: base64arr }).then(res => {
                    // console.log(res);
                    if (res.code == 200) {
                        console.log("发布成功");
                        navigation.navigate('MyCrops')
                    }
                })
            }
        }
        console.log(99999999);
        console.log(base64);
        setTimeout(() => {
            console.log(8888888);
            base64arr = []
        }, 2000)
    }
    const delimg = (index)=>{
        let arr = imgArr
        arr.splice(index, 1)
        console.log(arr);
        console.log(11111111);
        setArray(arr)
        setEff(eff+1)
    }
    return (
        <View style={{ backgroundColor: '#fff', width: '100%', height: '100%' }}>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between', padding: 10 }}>
                <Entypo name="chevron-thin-left" size={22} color="black" onPress={navigation.goBack} />
                <Btn style={{ backgroundColor: '#42C05C', width: 45, borderRadius: 8 }} color='#fff' onPress={publish}>记录</Btn>
            </View>
            <View style={styles.con}>
                <TextInput placeholder='记录一下植物的生长吧' multiline={true} value={value} onChangeText={text => onChangeText(text)}>
                </TextInput>
            </View>
            <View style={{ flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center' }}>
                {
                    imgArr.map((item, index) => {
                        return <View>
                            <TouchableOpacity style={styles.closeButton}>
                                <View style={[styles.closeCross, { transform: [{ rotate: "45deg" }] }]} />
                                <View
                                    style={[styles.closeCross, { transform: [{ rotate: "-45deg" }] }]}
                                />
                            </TouchableOpacity>
                            <View>
                                {/* <TouchableOpacity style={{ width: 100, height: 100, margin: 10 }} onPress={()=>setShowImg(true)}> */}
                                {/* <TouchableOpacity style={{ width: 100, height: 100, margin: 10 }} onPress={showModal}>
                                    <Image source={{ uri: item }} style={{ width: 100, height: 100 }}></Image>
                                </TouchableOpacity> */}
                                <View style={{ width: 100, height: 100, margin: 10, margin: 10}}>
                                    <AntDesign onPress={()=>{delimg(index)}} name="closecircleo" size={24} color="black" style={{marginBottom: -24, zIndex: 10, marginLeft: 76}}/>
                                    <Lightbox style={{ width: 100, height: 100 }}>
                                        <Image source={{ uri: item }} style={{ width: 100, height: 100 }}></Image>
                                    </Lightbox>
                                </View>

                            </View>
                        </View>
                    })
                }
                {imgArr.length<=3 && <TouchableOpacity style={{ width: 100, height: 100, margin: 10 }} onPress={showActionSheet}>
                    <Image source={require('../../../images/records/add.jpg')} style={{ width: 100, height: 100 }}></Image>
                </TouchableOpacity>}
            </View>
        </View>
    )
}
const styles = StyleSheet.create({
    imgs: {
        width: '20%',
        height: '20%',
        margin: 2
    },
    con: {
        height: '40%',
        margin: '5%'
    },
    textIn: {
        width: '100%',
        height: '100%',
    },
    container: {
        ...StyleSheet.absoluteFillObject
    },
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 22
    },
    modalView: {
        margin: 20,
        backgroundColor: "white",
        borderRadius: 20,
        padding: 35,
        alignItems: "center",
        shadowColor: "gray",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    openButton: {
        backgroundColor: "#F194FF",
        borderRadius: 20,
        padding: 10,
        elevation: 2
    },
    textStyle: {
        color: "white",
        fontWeight: "bold",
        textAlign: "center"
    },
    modalText: {
        marginBottom: 15,
        textAlign: "center"
    },
});
export default CropDetail